package com.jblv.frame.config.event;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author happyonion.yangtao
 * @version 1.0
 * @title ConfigChangeEventBus
 * @projectName jblv-frame
 * @packageName com.jblv.frame.config.event
 * @description TODO
 * @date Create at 2020/9/7 17:43
 * @since jdk1.8
 */
public class ConfigChangeEventBus {
    private static Logger logger ;
    private Map<String, ConfigChangeEventListener> listeners;
    private static ConfigChangeEventBus eventBus;

    private ConfigChangeEventBus() {
        logger =  LoggerFactory.getLogger(ConfigChangeEventBus.class);
        this.listeners = new ConcurrentHashMap<String, ConfigChangeEventListener>();
    }

    public static ConfigChangeEventBus build() {
        if (ConfigChangeEventBus.eventBus != null) {
            return ConfigChangeEventBus.eventBus;
        }
        synchronized (ConfigChangeEventBus.class) {
            if (ConfigChangeEventBus.eventBus != null) {
                return ConfigChangeEventBus.eventBus;
            }
            if (ConfigChangeEventBus.eventBus == null) {
                ConfigChangeEventBus.eventBus = new ConfigChangeEventBus();
            }
        }
        return ConfigChangeEventBus.eventBus;
    }

    private void listen(final ConfigChangeEvent event) {
        for (final ConfigChangeEventListener listener : this.listeners.values()) {
            try {
                if (!listener.isSupport(event)) {
                    continue;
                }
                listener.execute(event);
            }
            catch (Exception e) {
                logger.error(e.getMessage(), (Throwable)e);
            }
        }
    }

    public void postEvent(final ConfigChangeEvent event) {
        this.listen(event);
    }

    public void register(final ConfigChangeEventListener listener) {
        final String clazzName = listener.getClass().getName();
        if (this.listeners.containsKey(clazzName)) {
            return;
        }
        try {
            this.listeners.put(clazzName, listener);
            logger.info("ConfigChangeEventBus [" + clazzName + "] register.");
        }
        catch (Exception e) {
            logger.error(e.getMessage(), (Throwable)e);
        }
    }

     
}
